package com.compress4j.arithmetic.ppm;

import java.io.IOException;
import java.io.OutputStream;

import com.compress4j.arithmetic.Arithmetic;
import com.compress4j.arithmetic.ArithmeticEncoder;
/**
 * OutPutStream that encapsulate another one where it sill write PPMCompressed data
 * @author b.pierre
 *
 */
public class PPMOutputStream extends OutputStream{

	protected ArithmeticEncoder coder;
	private PPMTree<CompressionItem> ppmTree;

	public PPMOutputStream(OutputStream out, PPMTree<CompressionItem> ppmTree) throws IOException{
		coder = new Arithmetic.Coder(out);
		this.ppmTree = ppmTree;
	}

	public PPMOutputStream(OutputStream out, int PPMHigh, int PPMLow) throws IOException{
		this(out,new PPMTree<CompressionItem>(PPMHigh,PPMLow,CompressionItem.ALL_BYTE,new CompressionItem.Set()));
		out.write(PPMHigh);
		out.write(PPMLow);
	}
	@Override
	public void write(int b) throws IOException {
		CompressionItem word = CompressionItem.get(b);
		ppmTree.write(coder,word);
		ppmTree.handleUsedItem(word);
	}

	@Override
	public void close() throws IOException {
		ppmTree.write(coder,null);
		coder.close();
	}

	@Override
	public void flush() throws IOException {
		coder.flush();
	}

}
